package cn.zhj.tools;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class JsonUtils {
	/**
	 * 把json格式的字符串转为map对象 {"comp":"vetech","name":"123"}
	 */
	public static Map<String, String> jsonStr2Map(String str) {
		Map<String, String> map = new HashMap<String, String>();
		JSONObject json = JSONObject.fromObject(str);
		Iterator keys = json.keys();
		while (keys.hasNext()) {
			String key = (String) keys.next();
			String value = json.get(key).toString();
			if (value.startsWith("{") && value.endsWith("}")) {
				map.put(key, jsonStr2Map(value).toString());
			} else {
				map.put(key, value);
			}
		}
		return map;
	}

	/**
	 * 把json数组转为list对象 [{"comp":"vetech","name":"123"},{"comp":"test","name":"23"}]
	 */
	public static List<Map<String, String>> jsonArr2List(String jsonArrString) {
		List<Map<String, String>> list = new ArrayList<Map<String, String>>();
		if (jsonArrString.contains("[") && jsonArrString.contains("]")) {
			JSONArray jsArray = JSONArray.fromObject(jsonArrString);
			for (int i = 0; i < jsArray.length(); i++) {
				Map<String, String> map = new HashMap<String, String>();
				map = jsonStr2Map(jsArray.get(i).toString());
				list.add(map);
			}
		}
		return list;
	}

	/**
	 * 将java对象转换成json字符串
	 */
	public static String bean2JsonString(Object o) {
		JSONObject json;
		json = JSONObject.fromObject(o);
		return json.toString();
	}

	/**
	 * * 从json对象集合表达式中得到一个java对象列表 *
	 * @param jsonString  
	 * @param pojoClass  
	 * @return List
	 */

	public static List getList4Json(String jsonString, Class pojoClass){
		JSONArray jsonArray = JSONArray.fromObject(jsonString);
	 	JSONObject jsonObject;
 		Object pojoValue;
		 List list = new ArrayList();
		 for ( int i = 0 ; i<jsonArray.length(); i++){
		 jsonObject = jsonArray.getJSONObject(i);
		 pojoValue = JSONObject.toBean(jsonObject,pojoClass);
		 list.add(pojoValue);
		 }
		 return list;
	}

	public static void main(String[] args) {
		// String str="[{\"callmdn\":\"10655027021030\",\"mdn\":\"13237145660\"}]";
		// List map=JsonUtils.jsonArr2List(str);
		// System.out.println("32");
	}
}
